package com.liuc.task.cluster.demo.task2.util;

import com.liuc.task.cluster.demo.task2.exception.UnlockFailureException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTool {

    @Autowired
    private RedisTemplate<String, Object> rt;

    public Object get(String key) {
        return rt.opsForValue().get(key);
    }

    public void set(String key, Object value) {
        rt.opsForValue().set(key, value);
    }

    public boolean getLock(String key, Object value) {
       return rt.opsForValue().setIfAbsent(key, value);
    }

    public void releaseLockWithTimeout(String key,
                                       Long timeout,
                                       TimeUnit timeUnit) {
        rt.expire(key, timeout, timeUnit);
    }

    public void releaseLock(String key, String uuid) throws Exception {
        if (StringUtils.isBlank(uuid)) {
            throw new Exception("uuid 不可为空");
        }
        if (!StringUtils.contains(get(key).toString(), uuid)) {
            throw new UnlockFailureException("非加锁服务，解锁失败");
        }
        rt.delete(key);
    }


}
